package JUC.delayq;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class TestDelayQueue {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayElement> dq = new DelayQueue();
        dq.put(new DelayElement("A" , 1000*2));
        dq.put(new DelayElement("B" , 2000*2));
        dq.put(new DelayElement("D" , 3000*2));
        dq.put(new DelayElement("C" , 9000));
        System.out.println(dq.take());
        System.out.println(dq.take());
        System.out.println(dq.take());
        System.out.println(dq.take());

    }
    public static class DelayElement implements Delayed {
        private long endpoint ;
        private String name ;
        public DelayElement(String name , long future){
            this.name = name ;
            endpoint = System.currentTimeMillis() + future;
        }
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(endpoint - System.currentTimeMillis() , TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return (int)(this.endpoint - ((DelayElement)o).getEndpoint());
        }

        @Override
        public String toString() {
            return this.name;
        }

        public long getEndpoint() {
            return endpoint;
        }
    }
}
